const authService = require('../services/auth.service');
const { catchAsync } = require('../utils/error');

/**
 * 用户注册
 */
exports.register = catchAsync(async (req, res) => {
  const { username, email, password } = req.body;

  // 验证必填字段
  if (!username || !email || !password) {
    return res.status(400).json({
      success: false,
      message: '请提供用户名、邮箱和密码',
    });
  }

  // 注册用户
  const user = await authService.register({ username, email, password });

  return res.status(201).json({
    success: true,
    message: '注册成功',
    data: user,
  });
});

/**
 * 用户登录
 */
exports.login = catchAsync(async (req, res) => {
  const { email, password } = req.body;

  // 验证必填字段
  if (!email || !password) {
    return res.status(400).json({
      success: false,
      message: '请提供邮箱和密码',
    });
  }

  // 用户登录
  const { user, token } = await authService.login(email, password);

  return res.status(200).json({
    success: true,
    message: '登录成功',
    data: {
      user,
      token,
    },
  });
});

/**
 * 获取当前用户信息
 */
exports.getCurrentUser = catchAsync(async (req, res) => {
  res.status(200).json({
    success: true,
    data: req.user,
  });
});
